<?php
use Core\Helper\CommonHelper;

$treeData = $this->treeData;
$templateItem = $this->templateItem;
$allBlocks = $templateItem->getAllBlocks();
?>
<style type="text/css">


</style>

<div class="ad_title_ctn">
    <h2>Sửa template: <?php echo $templateItem->name ?></h2>
</div>
<div class="ad_content_ctn">
    <div class="control_ctn">
        <a href="javascript:saveTemplate();" class="k-button k-button-icontext k-grid-edit k-grid-edit k-grid-edit"><span>Lưu</span></a>
    </div>
    <fieldset style="margin: 10px 5px">
        <legend>Thông tin cơ bản</legend>
        <div id="basic_info_ctn">
            <table style="width:100%;" cellpadding="0" cellspacing="0">
                <tr>
                    <td style="width:60%; vertical-align: top;">
                        <div>

                            <div style="display: block;">
                                <div class="label_100 left">
                                    Tên:
                                </div>
                                <div class="left">
                                    <input value="<?php echo $templateItem->name ?>" id="txtName" name="txtName" style="width:250px" class="k-textbox" required validationMessage="Chưa nhập tên template">
                                    <span class="k-invalid-msg" data-for="txtName"></span>
                                </div>
                                <div class="clear"></div>
                            </div>
                            <div style="display: block;">
                                <div class="label_100 left">
                                    Mô tả:
                                </div>
                                <div style="float: left; ">
                                    <input value="<?php echo $templateItem->description ?>" id="txtDescription" name="txtDescription" style="width:450px"  class="k-textbox" required validationMessage="Chưa nhập mô tả template">
                                    <span class="k-invalid-msg" data-for="txtDescription"></span>
                                </div>
                                <div class="clear"></div>
                            </div>
                            <div style="display: block;">
                                <div class="label_100 left">
                                    Tên file:
                                </div>
                                <div style="float: left; ">
                                    <?php
                                    echo '<select id ="txtFile">';
                                    foreach (\Core\Helper\ApplicationDirectoryHelper::getAllTemplateFile() as $templateName) {
                                        echo '<option value="'.$templateName.'">'.$templateName.'</option>';
                                    }

                                    echo '</select>';
                                    ?>
                                </div>
                                <div class="clear"></div>
                            </div>

                        </div>
                    </td>
                    <td style="width:40%; vertical-align: top;">

                        <div style="padding-top: 5px;  text-decoration: underline; font: bold 1em Verdana, Arial, Helvetica, sans-serif;">
                            Ảnh mẫu template
                        </div>
                        <div style="padding: 5px 0px 5px 0px">
                            <a href="javascript:upImg()" id="lnkUpImage"  style="width:100px;"><span>Upload ảnh</span></a>
                            &nbsp;&nbsp;&nbsp;
                            <a href="javascript:removeImg()" id="lnkRemoveImage"  style="width:100px;"><span>Xóa ảnh</span></a>

                        </div>
                        <div style="padding: 5px">
                            <div style="padding: 5px ;height:150px; width:150px; border: 1px solid #CCC" align="center">
                                <img id="imgPresent" src="<?php echo  CommonHelper::getImagePath($templateItem->thumb_image) ?>" style="max-width:140px; max-height: 140px">


                            </div>
                            <div style="padding: 5px">
                                <span style="font: bold 12px Verdana, Arial, Helvetica, sans-serif;" id="spnImgPresent">
                                    <?php
                                        if($templateItem->file_name) echo $templateItem->thumb_image;
                                            else
                                                echo 'Chưa có ảnh thể hiện';

                                    ?>
                                </span>
                            </div>

                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </fieldset>

    <fieldset>
        <legend>Template</legend>
        <div style=" position: relative; padding: 5px" id="divTemplateContainer">

        </div>
        <!--<iframe src="" id="ifTemplateContainer" style="width: 100%; min-height: 500px">

        </iframe>-->
    </fieldset>

</div>

<div id="window" style="display: none">
    <div class="block_instance_chooser left">
        <div class="title">Danh sách block</div>
        <div id="treeview" ></div>
    </div>
    <div class="block_info left">
        <div class="title">Thông tin block</div>
        <div id="tabstrip">
            <ul>
                <li class="k-state-active">Hình ảnh mô tả</li>
                <li>Cấu hình</li>
                <li>Sử dụng bởi</li>
            </ul>
            <div class="content_ctn" id="blk_instance_view_ctn">
            </div>
            <div class="content_ctn" id="blk_instance_editor_ctn">

            </div>
            <div class="content_ctn" id="blk_instance_usage_ctn">
                Under construction :)
            </div>
        </div>
        <div class="control_ctn">
            <a id="lnkChooseBlock"  class="k-button k-button-icontext" style="width: 150px">Chọn</a>
        </div>


    </div>
    <div class="clear"></div>
</div>


<script type="text/javascript">
    var validator;
    var cboTemplateFile;
    var templateId = <?php echo $templateItem->id ?>;
    $(document).ready(function() {
       $("#txtFile").kendoComboBox({
            //make data limit in value set
            change : function (e) {
                if (this.value() && this.selectedIndex == -1) {
                    var dt = this.dataSource._data[0];
                    this.text(dt[this.options.dataTextField]);
                    this._selectItem();
                }
            }
        });
        cboTemplateFile = $("#txtFile").data("kendoComboBox");
        cboTemplateFile.value("<?php echo $templateItem->file_name ?>");

        validator = $("#basic_info_ctn").kendoValidator().data("kendoValidator");

        var treeDataAsJson = <?php echo $treeData ?>;
        $("#treeview").kendoTreeView({
            dataSource: treeDataAsJson,
            select: onSelect
        });

        var tabStrip = $("#tabstrip").kendoTabStrip({
            animation: { open: { effects: "fadeIn"} },
            select: onSelectTab
        });

        var treeview = $("#treeview").data("kendoTreeView");
        function onSelect(e) {
            blockNode = e.node
            loadBlockInstance(blockNode);
            loadBlockEditor(blockNode);

        }

        function loadBlockInstance(blockNode){

            parent = treeview.parent(blockNode);
            if(parent.length > 0){
                data = treeview.dataItem(blockNode);
                $('.block_info .title').html("Thông tin block " + data.text)
                $.post('/admin/block/get-block-view',{blockInstanceId:data.id }
                        ,function(result){
                            $('#tabstrip-1').html(result);
                        });
            }else{
                $('#tabstrip-1').html('<em>Chọn một block để hiển thị thông tin</em>');
            }
        }
        function loadBlockEditor(blockNode){

            parent = treeview.parent(blockNode);
            if(parent.length > 0){
                data = treeview.dataItem(blockNode);
                $('.block_info .title').html("Thông tin block " + data.text)
                $.post('/admin/block/get-block-editor',{blockInstanceId:data.id }
                        ,function(result){
                            $('#tabstrip-2').html(result);
                        });
            }else{
                $('#tabstrip-2').html('<em>Chọn một block để hiển thị thông tin</em>');
            }
        }



        function onSelectTab(e){
            tabName = $(e.item).find("> .k-link").text();
            blockNode = treeview.select();
            if(blockNode){
                if(tabName == 'Hình ảnh mô tả'){
                    loadBlockInstance(blockNode);
                }else if(tabName == 'Cấu hình'){

                    loadBlockEditor(blockNode);
                }
            }else{
                alert('Chọn một block để hiển thị thông tin');
            }

        }

        function chooseBlock(){
            blockNode = treeview.select();
            parent = treeview.parent(blockNode);
            if(parent.length > 0){
                data = treeview.dataItem(blockNode);

                $.post('/admin/block/get-block-view',{blockInstanceId:data.id }
                        ,function(result){
                            $('#'+currentDivId).html(result);
                            blockMap[currentDivId] = data.id;

                        });



            }else{
                $('#error_ctn').html('<em>Chọn một block để thêm.</em>');
            }


            windowBlockChooser.data("kendoWindow").close();
        }

        $('#lnkChooseBlock').click(function(){
            chooseBlock();
        })


        loadTemplate(cboTemplateFile.value());



    });


    function validate(){
        return validator.validate()
    }

    function saveTemplate(){
        if(!validate()) {
            return;
        }
        name = $("#txtName").val();
        description = $("#txtDescription").val();
        filePath = cboTemplateFile.value()
        imgPath = $("#spnImgPresent").html();

        tmpArr =  new Array();
        for (var obj in blockMap) {
            tmpArr.push(obj+"_"+blockMap[obj]);
        }
        $.post('/admin/template/save',{name:name,description:description, filePath:filePath,imgPath:imgPath
            , blockArr:tmpArr, templateId: templateId
        },function(result){
            if (result.success){
                window.location = "/admin/template"
            }else{
                $("#error_ctn").html(result.msg);
            }

        },'json');
    }

    function upImg(){
        try{
            var finder = new CKFinder();
            finder.basePath = '/public/js/ckfinder/';
            finder.selectActionFunction = setThumbFile;
            finder.popup();
        }catch(err){

        }
    }
    function setThumbFile( fileUrl )
    {
        $("#imgPresent").attr("src", $.getCmsThumb(fileUrl) );
        $("#spnImgPresent").html(fileUrl);
        $("#lnkRemoveImage").show();
    }

    function removeImg(){
        $("#imgPresent").attr("src", "/public/images/core/blank.jpg" );
        $("#spnImgPresent").html("");
        $("#lnkRemoveImage").hide();
        $("#lnkUpImage").show();
    }


    function loadTemplate(templateFile){

        $("#divTemplateContainer")
                .html(ajax_load)
                .load("/admin/template/load", {templateFile:templateFile, templateId: templateId},
                function(responseText){

                   /* $('#ifTemplateContainer').contents().find('html').html($("#divTemplateContainer").html())
                    $("#divTemplateContainer").html('');*/
                });

  /*      $('#ifTemplateContainer').contents().find('html').load(
            "/admin/template/load", {templateFile:templateFile, templateId: templateId});*/



        currentDivId = null;

    }


    $("#txtFile").change(function(){
        loadTemplate($(this).val());
        blockMap = [];

    })

    var windowBlockChooser = $("#window");
    function addBlock(divId){
        windowBlockChooser.kendoWindow({
            resizable: false,
            width: "950px",
            height: "550px",
            title: "Chọn block cần thêm(thay) vào template",
            actions: [
                "Maximize",
                "Close"
            ]
        });
        currentDivId = divId;
        windowBlockChooser.data("kendoWindow").center().open();
    }

    function removeBlock(divId){
        $('#'+divId).html('');
        delete blockMap[currentDivId];
    }
    var currentDivId;
    var blockMap = [];
    <?php
    foreach ($allBlocks as $aBlockInstance) {
        echo 'blockMap["'.$aBlockInstance->div_id.'"] = '.$aBlockInstance->id.'; ';
    }

    ?>


</script>

